package com.example.blogdemo.service;

import com.example.blogdemo.entity.ArticleTag;
import com.example.blogdemo.entity.Tag;
import com.example.blogdemo.repository.ArticleTagRepository;
import com.example.blogdemo.repository.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2017-12-15
 **/
@Service
public class TagService {


    @Autowired
    private TagRepository tagRepository;

    @Autowired
    private ArticleTagRepository articleTagRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Tag selectByName(String name) {
        return tagRepository.findByName(name);
    }

    public List<Tag> getAllTag(){
        return tagRepository.findAll();
    }

    public int addTag(Tag tag){
        return tagRepository.save(tag).getId();
    }

    public int addArticleTag(ArticleTag articleTag){
        return  articleTagRepository.save(articleTag).getId();
    }

    public void updateCount(int tagId,int count){
        tagRepository.updateCountByTagId(tagId,count);
    }

    public List<Tag> getTagByArticleId(int articleId){

        String querySql = String.format("select id,name,count from tag where id in (select tag_id from article_tag where article_id =%d )", articleId);
        RowMapper<Tag> rowMapper = new BeanPropertyRowMapper<>(Tag.class);
        return jdbcTemplate.query(querySql,rowMapper);
    }

    public List<Tag> getTagByUserId(Integer userId){
        return tagRepository.findByUserId(userId);
    }


}


